package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.cargo.*;
import com.itheima.other.ResultInfo;
import com.itheima.service.cargo.ContractService;
import com.itheima.service.cargo.ExportProductService;
import com.itheima.service.cargo.ExportService;
import com.itheima.service.cargo.PackingService;
import com.itheima.web.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 装箱管理控制器
 */
@Slf4j
@Controller
@RequestMapping("/cargo/packing")
public class PackingController extends BaseController {

    @Reference
    private ExportProductService exportProductService;
    @Reference
    private ContractService contractService;
    @Reference
    private ExportService exportService;
    @Reference
    private PackingService packingService;

    /**
     * 从报运单列表出进入点击装箱，处理是否可用装箱
     *
     * @param id
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public ResultInfo packingAdd(String id) {
        if (id == null || "".equals(id)) {
            return new ResultInfo(false, "请勾选需要装箱的运单");
        }
        String[] split = id.split(",");
        List<String> exportIds = Arrays.asList(split);
        //String state = "";     //报运单状态
        String consignee = "";     //收货地址
        String shipmentPort = "";        //装运港
        String destinationPort = "";   //目的港
        String transportMode = "";     //运输方式
        for (String exportId : exportIds) {
            Export export = exportService.findById(exportId);
            //判断报运单状态
            if (export.getState() != 2) {
                return new ResultInfo(false, "请勾选已经报运的报运单");
            }
            //判断收货地址是否相同
            if (!consignee.equals("") && !consignee.equals(export.getConsignee())) {
                return new ResultInfo(false, "收货人及地址不同不能一起装箱");
            }
            consignee = export.getConsignee();
            //判断装运港是否相同
            if (!shipmentPort.equals("") && !shipmentPort.equals(export.getShipmentPort())) {
                return new ResultInfo(false, "装运港不同不能一起装运");
            }
            shipmentPort = export.getShipmentPort();
            //判断目的港是否相同
            if (!destinationPort.equals("") && !destinationPort.equals(export.getDestinationPort())) {
                return new ResultInfo(false, "目的港不同不能一起装运");
            }
            destinationPort = export.getDestinationPort();
            //判断运输方式
            if (!transportMode.equals("") && !transportMode.equals(export.getTransportMode())) {
                return new ResultInfo(false, "运输方式不一样不能一起装运");
            }
            transportMode = export.getTransportMode();
        }
        return new ResultInfo<String>(true, "", "" + id);
    }

    //准备装箱添加页面显示数据
    @RequestMapping("/toAdd")
    public String toAdd(String id) {
        String[] split = id.split(",");
        List<String> exportIds = Arrays.asList(split);
        //创建空集装箱对象
        Packing packing = new Packing();
        packing.setExportIds(id);//储存报运单id
        String contractNo = "";//存储合同号
        String shipmentPort = "";//装运港
        ExportExample example = new ExportExample();
        example.createCriteria().andIdIn(exportIds);
        //遍历所有运单
        List<Export> list = exportService.selectByExample(example);
        for (int i = 0; i < list.size(); i++) {
            Export export = list.get(i);
            shipmentPort = export.getShipmentPort();//获取装运港
            //export.setState(3);//设置运单为装箱状态
            String contractIds = export.getContractIds();
            String[] split1 = contractIds.split(",");
            List<String> strings = Arrays.asList(split1);
            //遍历运单的所有合同号
            for (int i1 = 0; i1 < strings.size(); i1++) {
                Contract contract = contractService.findById(strings.get(i1));
                if (contract == null) {
                    continue;
                }
                if (i == (list.size() - 1) && i1 == strings.size() - 1) {
                    contractNo += contract.getContractNo();
                } else {
                    contractNo += (contract.getContractNo() + ",");
                }
            }
        }
        packing.setExportNos(contractNo);//存储合同号
        packing.setPackingAddress(shipmentPort);//储存装运港
        packing.setState(0l);//设置为草稿

        List<Packing> packingList = new ArrayList<>();
        packingList.add(packing);
        int j = 0;
        Double sumSizeVolume = 0d;//装箱单总体积
        Double sumSizeGross = 0d;//装箱单总毛重
        Double sumSizeNet = 0d;//装箱单总净重
        Double sumMoney = 0d;//装箱单总费用


        //遍历多个报运单
        for (String exportId : exportIds) {
            ExportProductExample exportProductExample = new ExportProductExample();
            exportProductExample.createCriteria().andExportIdEqualTo(exportId);
            List<ExportProduct> products = exportProductService.findAll(exportProductExample);

            //遍历报运单下所有商品
            for (int i = 0; i < products.size(); i++) {
                ExportProduct product = products.get(i);
                if (product == null) {
                    continue;
                }
                //总体积超了要分箱
                if (packingList.get(j).getTotalVolume() != null && packingList.get(j).getTotalVolume() > 2100) {
                    //减去前一个箱子货物
                    Double totalVolume = packingList.get(j).getTotalVolume();
                    packingList.get(j).setTotalVolume(totalVolume -
                            (products.get(i - 1).getSizeLength() * products.get(i - 1).getSizeWidth() * products.get(i - 1).getSizeHeight()));
                    //减去前一个箱子的净重
                    Double netWeights = packingList.get(j).getNetWeights();
                    packingList.get(j).setNetWeights(netWeights - products.get(i - 1).getNetWeight());
                    //减去前一个箱子的毛重
                    Double grossWeights = packingList.get(j).getGrossWeights();
                    packingList.get(j).setGrossWeights(grossWeights - products.get(i - 1).getGrossWeight());

                    Packing packing1 = new Packing();
                    packing1.setExportIds(id);//储存报运单id
                    packing1.setExportNos(contractNo);//存储合同号
                    packing1.setPackingAddress(shipmentPort);//储存装运港
                    packing.setState(0l);//设置为草稿
                    packingList.add(packing1);
                    j++;

                    //第二个箱子加上第一个箱子减去的货物
                    packingList.get(j).setTotalVolume((products.get(i - 1).getSizeLength() * products.get(i - 1).getSizeWidth() * products.get(i - 1).getSizeHeight()));
                    totalVolume = packingList.get(j).getTotalVolume();
                    packingList.get(j).setTotalVolume(totalVolume + (product.getSizeLength() * product.getSizeWidth() * product.getSizeHeight()));
                    //第二个箱子加上第一个箱子减去的净重
                    packingList.get(j).setNetWeights(products.get(i - 1).getNetWeight());
                    netWeights = packingList.get(j).getNetWeights();
                    packingList.get(j).setNetWeights(netWeights + product.getNetWeight());
                    //第二个箱子加上第一个箱子减去的毛重
                    packingList.get(j).setGrossWeights(products.get(i - 1).getGrossWeight());
                    grossWeights = packingList.get(j).getGrossWeights();
                    packingList.get(j).setGrossWeights(grossWeights + product.getGrossWeight());
                } else {
                    //计算总体积，货物长乘宽乘高
                    Double totalVolume = packingList.get(j).getTotalVolume();
                    packingList.get(j).setTotalVolume(totalVolume + (product.getSizeLength() * product.getSizeWidth() * product.getSizeHeight()));
                    //计算总净重
                    Double netWeights = packingList.get(j).getNetWeights();
                    packingList.get(j).setNetWeights(netWeights + product.getNetWeight());
                    //计算总毛重
                    Double grossWeights = packingList.get(j).getGrossWeights();
                    packingList.get(j).setGrossWeights(grossWeights + product.getGrossWeight());
                }
            }

        }

        Packing packing1 = new Packing();
        //计算总数据
        for (int i = 0; i < packingList.size(); i++) {
            //单个集装箱的总费用
            packingList.get(i).setPackingMoney(packingList.get(i).getGrossWeights() * 520);
            sumSizeVolume += packingList.get(i).getTotalVolume();//装箱单总体积
            sumSizeGross += packingList.get(i).getGrossWeights();//装箱单总毛重
            sumSizeNet += packingList.get(i).getNetWeights();//装箱单总净重
            sumMoney += packingList.get(i).getPackingMoney();//装箱单总费用
        }
        packing1.setTotalVolume(sumSizeVolume);
        packing1.setGrossWeights(sumSizeGross);
        packing1.setNetWeights(sumSizeNet);
        packing1.setPackingMoney(sumMoney);
        //ResultInfo<List<Packing>> listResultInfo = new ResultInfo<>(packingList);
        session.setAttribute("resultInfo", new ResultInfo<List<Packing>>(packingList));

        //
        request.setAttribute("packing", packing1);
        //存储合同号
        request.setAttribute("contractNo", contractNo);
        return "cargo/packing/packing_add";
    }

    //保存或修改装箱单，然后跳转到列表
    @RequestMapping("/edit")
    public String edit(Packing packing) {
        ResultInfo<List<Packing>> resultInfo = (ResultInfo<List<Packing>>) session.getAttribute("resultInfo");
        List<Packing> packingList = resultInfo.getData();
        String packingListId = packing.getPackingListId();
        for (int i = 0; i < packingList.size(); i++) {
            Packing packingSave = packingList.get(i);
            packingSave.setId(UUID.randomUUID().toString());
            packingSave.setPackingListId(packingListId + "-" + (i + 1));//保存集装箱号
            packingSave.setPackingTime(packing.getPackingTime());//保存装箱时间
            packingSave.setMarks(packing.getMarks());//设置唛头
            packingSave.setDescriptions(packing.getDescriptions());//设置描述信息
            packingSave.setState(0l);//设置集装箱为草稿状态
            packingService.save(packingSave);
        }
        return "redirect:/cargo/packing/list";
    }

    //装箱管理列表
    @RequestMapping("/list")
    public String packingList(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "5") int pageSize) {
        PageInfo<Packing> byPage = packingService.findByPage(new PackingExample(), pageNum, pageSize);
        request.setAttribute("pageInfo", byPage);
        return "cargo/packing/packing-packingList";
    }

    //集装箱的删除
    @RequestMapping("/delete")
    public String delete(String id) {
        String[] split = id.split(",");
        //遍历所有的集装箱并删除
        for (String s : split) {
            packingService.delete(s);
        }
        return "redirect:/cargo/packing/list";
    }


}
